import BenefitAPI from '@/api/Benefit';
import { Box, useCall, useReq } from '@/components';
import { forkHandler } from '@/utils';
import { message, Spin } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import BenefitDescTable from './BenefitDescTable';
import { useDefinitionData } from './Context';

function BenefitDescConfig(props, ref) {
  const definitionData = useDefinitionData();
  const { productCode } = definitionData?.productDefineList?.[0] ?? {};
  const xhr = useReq(BenefitAPI.getTree);
  const batchXhr = useReq(BenefitAPI.batchUpdate);
  const tableRef = useRef();
  const shouldRefreshRef = useRef(true);

  const refresh = useCall(() => !shouldRefreshRef.current || xhr.start({ planCode: productCode, type: 0 }));

  const onSave = useCall(() => {
    // shouldRefreshRef.current = false;
    return tableRef?.current?.onSave();
  });

  useImperativeHandle(
    ref,
    () => ({
      onSave,
    }),
    [],
  );

  useEffect(() => {
    if (productCode) refresh();
  }, [productCode]);

  const [dataSource, setData] = useState([]);

  useEffect(() => {
    if (xhr.result?.data) setData(xhr.result.data);
  }, [xhr.result]);

  const loading = [xhr.status, batchXhr.status].includes('loading');

  return (
    <Box grow scroll>
      <Spin spinning={loading}>
        <BenefitDescTable
          ref={tableRef}
          dataSource={dataSource}
          onChange={useCall(
            forkHandler(
              batchXhr.start,
              () => {
                message.success('保存成功');
              },
              refresh,
              true,
            ),
          )}
          onRemove={useCall(
            forkHandler(
              (item) => item.id && BenefitAPI.remove([item.id]),
              () => {
                message.success('删除成功');
              },
              true,
            ),
          )}
          planCode={productCode}
          productCode={productCode}
        />
      </Spin>
    </Box>
  );
}

BenefitDescConfig = forwardRef(BenefitDescConfig);

export default BenefitDescConfig;
